package com.bjpowernode.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.enums.Code;
import com.bjpowernode.utils.JwtUtil;
import com.bjpowernode.web.views.ResultView;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @description:
 * @author: panDeng_Zhu
 * @time: 2022/11/12 11:34
 */

public class TokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    private String userSecretKey;

    public TokenInterceptor() {
    }

    public TokenInterceptor(StringRedisTemplate stringRedisTemplate, String userSecretKey) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.userSecretKey = userSecretKey;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("执行了拦截器 preHandle METHOD" + request.getMethod()
                + ",url=" + request.getRequestURI());
        boolean checkToken = false;
        //预处理请求，拦截器返回true
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //获取token，验证token
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(authorization)) {
            if (authorization.indexOf("Bearer") >= 0) {
                String jwt = authorization.substring(7);
                //接下来看redis中是否有这个token
                if (stringRedisTemplate.hasKey(jwt)) {
                    //token用户退出的
                    checkToken = false;
                } else {
                    //验证token，使用jwt库

                    try {
                        JwtUtil jwtUtil = new JwtUtil(userSecretKey);
                        Claims claims = jwtUtil.readToken(jwt);
                        //从jwt中获取userId
                        Integer userId = claims.get("userId", Integer.class);

                        String headerUid = request.getHeader("userId");
                        if (String.valueOf(userId).equals(headerUid)) {
                            //token和userId都是可用的，可以访问系统
                            checkToken = true;
                        }
                    } catch (Exception e) {
                        checkToken = false;
                        e.printStackTrace();
                    }
                }
            }
        }

        //token访问失败，返回错误信息
        if (checkToken == false) {
            response.setContentType("application/json;charset=utf-8");
            ResultView<String> result = ResultView.FAIL();
            result.setEnumCode(Code.TOKEN_INVLID);
            //把result-->json
            String json = JSONObject.toJSONString(result);
            //输出json
            PrintWriter out =response.getWriter();
            out.println(json);
            out.flush();
            out.close();
        }
        return checkToken;
    }
}
